package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.InterfaceDto;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.*;
import com.ysd.lis.service.SysInterfaceMethValueService;
import com.ysd.lis.service.SysInterfaceService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2022-02-05
 */
@Service
@Slf4j
public class SysInterfaceMethValueServiceImpl extends ServiceImpl<SysInterfaceMethValueMapper, SysInterfaceMethValue> implements SysInterfaceMethValueService {

    @Autowired
    SysParamMapper sysParamMapper;
    @Autowired
    SysInterfaceDictFieldMapper sysInterfaceDictFieldMapper;

    @Autowired
    SysInterfaceMethValueMapper sysInterfaceMethValueMapper;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Override
    public Result findSysParamInfoByCode(SysParamParam param) throws JsonProcessingException {
        LambdaQueryWrapper<SysParam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysParam::getDelFlag, 0).eq(SysParam::getCode, param.getParamCode());
        SysParam sysParam = sysParamMapper.selectOne(queryWrapper);
        SysParamDto sysParamDto = new SysParamDto();
        if (ToolsUtils.isNotEmpty(sysParam)) {
            BeanUtil.copyProperties(sysParam, sysParamDto);
            //查询分组
            LambdaQueryWrapper<SysInterfaceDictField> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysInterfaceDictField::getDelFlag, 0)
                    .eq(SysInterfaceDictField::getGrade, 0)
                    .eq(SysInterfaceDictField::getPid, sysParam.getId())
                    .orderByAsc(SysInterfaceDictField::getSeq);
            List<SysInterfaceDictField> groupList = sysInterfaceDictFieldMapper.selectList(queryWrapper1);
            if (ToolsUtils.isNotEmpty(groupList)) {
                //查询分组下的字段属性集合
                List<String> groupIds = groupList.stream().map(SysInterfaceDictField::getId).collect(Collectors.toList());

                LambdaQueryWrapper<SysInterfaceDictField> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(SysInterfaceDictField::getDelFlag, 0)
                        .eq(SysInterfaceDictField::getGrade, 1)
                        .in(SysInterfaceDictField::getPid, groupIds)
                        .orderByAsc(SysInterfaceDictField::getSeq);
                List<SysInterfaceDictField> fieldList = sysInterfaceDictFieldMapper.selectList(queryWrapper2);
                List<SysParamFieldDto> fmItems = new ArrayList<>();
                Integer j = 0;
                for (SysInterfaceDictField item : fieldList) {
                    SysParamFieldDto fmitm = new SysParamFieldDto();
                    BeanUtil.copyProperties(item, fmitm, "fieldOptions");
                    fmitm.setVisible(1);
                    fmitm.setIsCurrent(j == 0);
                    if (ToolsUtils.isNotEmpty(item.getFieldSource()) && item.getFieldSource().equals("3") && ToolsUtils.isNotEmpty(item.getFieldOptions())) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        SysFieldOptionsDto[] ops = objectMapper.readValue(item.getFieldOptions(), SysFieldOptionsDto[].class);
                        fmitm.setFieldOptions(Arrays.asList(ops));
                    }
                    fmItems.add(fmitm);
                    j++;
                }


                //组合分组
                List<SysParamGroupDto> groupDtoList = new ArrayList<>();
                for (SysInterfaceDictField field : groupList) {
                    SysParamGroupDto groupDto = new SysParamGroupDto();
                    BeanUtil.copyProperties(field, groupDto);
                    groupDto.setParamFieldList(fmItems.stream().filter(i -> i.getPid().equals(field.getId())).collect(Collectors.toList()));
                    groupDtoList.add(groupDto);
                }
                sysParamDto.setParamGroupList(groupDtoList);
            }
        }


        return Result.succ(1, "查询成功", sysParamDto);
    }

    @Override
    public Result saveInterfaceMethValueList(InterfaceDto dto) throws JsonProcessingException {

        List<SysInterfaceMethValue> editSysParamValueList = dto.getMethValueList();
        List<String> fieldIds = new ArrayList<>();

        List<String> stringList = editSysParamValueList.stream().map(SysInterfaceMethValue::getFieldId).collect(Collectors.toList());
        fieldIds.addAll(stringList);
        //查询历史数据
        LambdaQueryWrapper<SysInterfaceMethValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysInterfaceMethValue::getDelFlag, 0)
                .in(SysInterfaceMethValue::getFieldId, fieldIds);
        if (ToolsUtils.isNotEmpty(dto.getMethodId())) {
            queryWrapper.eq(SysInterfaceMethValue::getMethodId, dto.getMethodId());
        }
        List<SysInterfaceMethValue> oldParamValueList = sysInterfaceMethValueMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(oldParamValueList)) {
            for (SysInterfaceMethValue paramValue : editSysParamValueList) {
                Optional<SysInterfaceMethValue> first = oldParamValueList.stream().filter(o -> (o.getFieldId().equals(paramValue.getFieldId()))).findFirst();
                if (first.isPresent()) {
                    SysInterfaceMethValue paramValue1 = first.get();
                    paramValue.setId(paramValue1.getId());
                }
            }
        }
        boolean b = this.saveOrUpdateBatch(editSysParamValueList);
        return Result.succ(1, "提交成功", null);
    }

    @Override
    public Result findInterfaceMethValueList(InterfaceDictParam param) {
        HashMap<String, Object> returnMap = new HashMap<>();
            MPJLambdaWrapper<SysInterfaceMethValue> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(SysInterfaceMethValue.class)
                    .leftJoin(SysInterfaceDictField.class, "sf", SysInterfaceDictField::getId, SysInterfaceMethValue::getFieldId)
                    .eq(SysInterfaceMethValue::getDelFlag, 0)
                    .eq("sf.DEL_FLAG", 0)
                    .eq(StrUtil.isNotEmpty(param.getDictId()),SysInterfaceDictField::getPid, param.getDictId())
                    .eq(StrUtil.isNotEmpty(param.getMethodId()),SysInterfaceMethValue::getMethodId,param.getMethodId())
                    .eq(StrUtil.isNotEmpty(param.getId()),SysInterfaceMethValue::getFieldId,param.getId());

        List<SysInterfaceMethValue> valueList = sysInterfaceMethValueMapper.selectList(queryWrapper);

            returnMap.put("fmValues", valueList);


        return Result.succ(1, "查询成功", returnMap);
    }

    @Override
    public Result findInterfaceMethValueListByModuleIdAndSystemId(InterfaceDictParam param) {
        List<SysInterfaceMethValue> valueList = new ArrayList<>();
        LambdaQueryWrapper<SysInterface> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysInterface::getSystemId,param.getSystemId())
                .eq(SysInterface::getModuleId,param.getModuleId())
                .eq(SysInterface::getDelFlag,0);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(lambdaQueryWrapper);
        List<String> collect = sysInterfaces.stream().map(SysInterface::getId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(collect)){

            MPJLambdaWrapper<SysInterfaceMethValue> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(SysInterfaceMethValue.class)
                    .selectAs(SysInterfaceDictField::getTitle, SysInterfaceMethValue::getTitle)
                    .selectAs(SysInterface::getInterfaceName, SysInterfaceMethValue::getInterfaceName)
                    .selectAs(SysInterfaceDict::getName, SysInterfaceMethValue::getMethodName)
                    .leftJoin(SysInterfaceDictField.class, "sf", SysInterfaceDictField::getId, SysInterfaceMethValue::getFieldId)
                    .leftJoin(SysInterface.class, "inter", SysInterface::getId, SysInterfaceMethValue::getInterfaceId)
                    .leftJoin(SysInterfaceDict.class, "dict", SysInterfaceDict::getId, SysInterfaceMethValue::getDictId)
                    .eq(SysInterfaceMethValue::getDelFlag, 0)
                    .eq("sf.DEL_FLAG", 0)
                    .in(SysInterfaceMethValue::getInterfaceId,collect)
            .like(StrUtil.isNotEmpty(param.getTitle()),"dict.name",param.getTitle());
            valueList = sysInterfaceMethValueMapper.selectList(queryWrapper);
        }
        return Result.succ(1, "查询成功", valueList);
    }


    @Override
    public Result findSysParamFieldAndValueByCode(SysParamParam param) throws JsonProcessingException {
        MPJLambdaWrapper<SysInterfaceMethValue> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysInterfaceDictField.class, "sf")
                .selectAs(SysInterfaceMethValue::getId, SysParamFieldValueDto::getValueId)
                .selectAs(SysInterfaceMethValue::getClassify, SysParamFieldValueDto::getClassify)
                .selectAs(SysInterfaceMethValue::getClassifyId, SysParamFieldValueDto::getClassifyId)
                .selectAs(SysInterfaceMethValue::getValue, SysParamFieldValueDto::getValue)
                .selectAs(SysInterfaceMethValue::getDataType, SysParamFieldValueDto::getDataType)
                .selectAs(SysInterfaceMethValue::getIsLocal, SysParamFieldValueDto::getIsLocal)
                .selectAs(SysInterfaceMethValue::getLocalComputer, SysParamFieldValueDto::getLocalComputer)
                .leftJoin(SysInterfaceDictField.class, "sf", SysInterfaceDictField::getId, SysInterfaceMethValue::getFieldId)
                .leftJoin(SysInterfaceDictField.class, "sg", SysInterfaceDictField::getId, SysInterfaceDictField::getPid)
                .leftJoin(SysParam.class, "sp", SysParam::getId, SysInterfaceDictField::getPid);
        queryWrapper.eq(SysInterfaceMethValue::getDelFlag, 0)
                .eq("sf.DEL_FLAG", 0)
                .eq("sg.DEL_FLAG", 0)
                .eq("sp.DEL_FLAG", 0)
                .eq("sf.grade", 1)
                .eq("sg.grade", 0)
                .eq(SysParam::getCode, param.getParamCode());
        if (ToolsUtils.isNotEmpty(param.getClassifyId())) {
            queryWrapper.eq(SysInterfaceMethValue::getClassifyId, param.getClassifyId());
        }
        if (ToolsUtils.isNotEmpty(param.getLocalComputer())) {
            queryWrapper.eq(SysInterfaceMethValue::getLocalComputer, param.getLocalComputer());
        }
        if (ToolsUtils.isNotEmpty(param.getField())) {
            queryWrapper.eq("sf.FIELD", param.getField());
        }
        List<SysParamFieldValueDto> valueList = sysInterfaceMethValueMapper.selectJoinList(SysParamFieldValueDto.class, queryWrapper);
        return Result.succ(1, "查询成功", valueList);
    }

    public List<SysParamFieldValueDto> findSysParamFieldAndValueListByCode(SysParamParam param) throws JsonProcessingException {
        MPJLambdaWrapper<SysInterfaceMethValue> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysInterfaceDictField.class, "sf")
                .selectAs(SysInterfaceMethValue::getId, SysParamFieldValueDto::getValueId)
                .selectAs(SysInterfaceMethValue::getClassify, SysParamFieldValueDto::getClassify)
                .selectAs(SysInterfaceMethValue::getClassifyId, SysParamFieldValueDto::getClassifyId)
                .selectAs(SysInterfaceMethValue::getValue, SysParamFieldValueDto::getValue)
                .selectAs(SysInterfaceMethValue::getDataType, SysParamFieldValueDto::getDataType)
                .selectAs(SysInterfaceMethValue::getIsLocal, SysParamFieldValueDto::getIsLocal)
                .selectAs(SysInterfaceMethValue::getLocalComputer, SysParamFieldValueDto::getLocalComputer)
                .leftJoin(SysInterfaceDictField.class, "sf", SysInterfaceDictField::getId, SysInterfaceMethValue::getFieldId)
                .leftJoin(SysInterfaceDictField.class, "sg", SysInterfaceDictField::getId, SysInterfaceDictField::getPid)
                .leftJoin(SysParam.class, "sp", SysParam::getId, SysInterfaceDictField::getPid);
        queryWrapper.eq(SysInterfaceMethValue::getDelFlag, 0)
                .eq("sf.DEL_FLAG", 0)
                .eq("sg.DEL_FLAG", 0)
                .eq("sp.DEL_FLAG", 0)
                .eq("sf.grade", 1)
                .eq("sg.grade", 0)
                .eq(SysParam::getCode, param.getParamCode());
        if (ToolsUtils.isNotEmpty(param.getClassifyId())) {
            queryWrapper.eq(SysInterfaceMethValue::getClassifyId, param.getClassifyId());
        }
        if (ToolsUtils.isNotEmpty(param.getLocalComputer())) {
            queryWrapper.eq(SysInterfaceMethValue::getLocalComputer, param.getLocalComputer());
        }
        if (ToolsUtils.isNotEmpty(param.getField())) {
            queryWrapper.eq("sf.FIELD", param.getField());
        }
        List<SysParamFieldValueDto> valueList = sysInterfaceMethValueMapper.selectJoinList(SysParamFieldValueDto.class, queryWrapper);
        return valueList;
    }
}
